package com.daoImpl;

import com.dao.BasicDAO;
import com.dao.UserDAO;
import com.bean.User;
import org.junit.jupiter.api.Test;

/**
 * @author 徐洲
 * @version 1.0
 * 用户相关的操作
 */
public class UserDAOImpl extends BasicDAO<User> implements UserDAO {

	@Test
	public void test(){
		String sql = "select * from `users` where username=? and password=md5(?)";
		User user = querySingle(sql, User.class, "test", "123");
		System.out.println(user.getUserid());
	}

	/**
	 * 用户登录
	 */
	@Override
	public Integer userLogin(String username, String password){
		String sql = "select * from `users` where username=? and password=md5(?)";
		User user = querySingle(sql, User.class, username, password);
		if (user == null) return -1;
		return user.getUserid();
	}

	/**
	 * 判断原密码是否相同
	 */
	@Override
	public boolean userIfPwd(String oldPwd, String username){
		String sql = "SELECT md5(?) = `password` FROM users WHERE username = ?";
		return (Long)queryScalar(sql, oldPwd, username) > 0;
	}

	/**
	 * 用户注册
	 */
	@Override
	public boolean userRegister(String username, String password, String email){
		String sql = "insert into `users` (`username`, `password`,`email`, `avatar`) values (?,md5(?),?,'img.png')";
		Integer integer = update(sql, username, password, email);
		if (integer == null) return false;
		return  integer> 0;
	}


	/**
	 * 修改用户密码
	 */
	@Override
	public boolean userChangePassword(String password, String username){
		String sql = "update `users` set password=md5(?) where username=?";
		Integer integer = update(sql, password, username);
		if (integer == null) return false;
		return  integer> 0;
	}


	/**
	 * 修改用户信息
	 */
	@Override
	public boolean userChangeInfo(User user) {
		String sql = "update `users` set sex=?, telephone=?, email=? where username=?";
		Integer integer = update(sql, user.getSex(), user.getTelephone(), user.getEmail(), user.getUsername());
		if (integer == null) return false;
		return  integer > 0;
	}

	/**
	 * 修改用户头像
	 */
	@Override
	public boolean changeAvatar(String filename, String username){
		String sql = "update `users` set avatar=? where username=?";
		Integer integer = update(sql, filename, username);
		if (integer == null) return false;
		return  integer > 0;
	}


	/**
	 * 得到用户信息
     */
	@Override
	public User getUserInfo(String username) {
		String sql = "select * from `users` where username = ?";
		return querySingle(sql, User.class, username);
	}
}
